package com.fg.cloud.factory.controller.agency;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.file.excel.ExcelBean;
import com.fg.cloud.common.file.excel.ExcelUtils;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.agency.AgencyUserEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.service.agency.AgencyUserService;

/**
 * 经销商用户controller
 * @author around
 * @date 2017-6-22
 */
@Controller
@RequestMapping("/agencyUser")
public class AgencyUserController extends BaseController {

	@Autowired
	private AgencyUserService agencyUserService;
	
	/**
	 * 详情页信息封装查询
	 * @param request
	 * @param session
	 * @param user
	 * @return String 
	 */
	@RequestMapping(value = "/detail", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void openPage(HttpServletRequest request, HttpServletResponse response, 
			AgencyUserEntity user) {
		try {
			user = agencyUserService.find(user.getId());
			if(user == null)
				doResult(response, false, StatusCode.FINDERROR, null, ResultType.FIND_NULL);
			else
				doResult(response, true, StatusCode.FINDSUCCESS, user, ResultType.FIND_SUCCESS);
		} catch (NullPointerException e) {
			doResult(response, false, StatusCode.LACKVALUE, null, ResultType.INPUT_NULL);
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 分页查询
	 * @param request
	 * @param session
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param user
	 */
	@RequestMapping(value = "/findList", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void findList(HttpServletRequest request, HttpServletResponse response, 
			Integer page, Integer rows, String sort, String order,
			String filter, Long ageId) {
		try {
			PageUtils<AgencyUserVo> pageinfo = new PageUtils<AgencyUserVo>(page, rows, sort, order); 
			Map<String, Object> condition = pageinfo.getCondition();
			//ParamsReflect.getParamsByReflect(user);
			condition.put("facId", getCurrentFactoryUser().getFacId());
			condition.put("ageId", ageId);
			condition.put("filter", filter);
			
			agencyUserService.findList(pageinfo);
			
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(response, false, StatusCode.FINDERROR, null, ResultType.FIND_FAULT);
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增/保存信息
	 * @param request
	 * @param response
	 * @param user AgencyUserEntity
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	@ResponseBody
	public void saveOrUpdate(HttpServletRequest request, HttpServletResponse response, 
			AgencyUserEntity user) {
		if(null == user.getAgeId()) {
			doResult(response, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
			return;
		}
		try {
			boolean flag = agencyUserService.verifyUniquely(user.getId(), user.getUserName());
			if (!flag) {
				doResult(response, false, StatusCode.SAVEERROR, null, "重复的用户名");
				return;
			}
			
			setUpdateInfo(user, request);
			//id为空新增、不为空保存
			if(LongUtils.isEmpty(user.getId())) {
				setCreateInfo(user, request);
				user.setFacId(getCurrentFactoryUser().getFacId());
				//存储新密码
				//user.setPassword(DigestUtils.md5Hex(user.getPassword()));
				user.setPassword(DigestUtils.md5Hex("123456"));
				flag = agencyUserService.insertSelective(user);
			} else {
				////存储新密码
				if(StringUtils.isNotEmpty(user.getPassword()))
					user.setPassword(DigestUtils.md5Hex(user.getPassword()));
				flag = agencyUserService.updateByPrimaryKeySelective(user);
			}
			doResult(response, flag, flag ? StatusCode.SAVESUCCESS:StatusCode.SAVEERROR, 
					null, flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.SAVEERROR, null, ResultType.SAVE_FAULT);
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除信息
	 * @param request
	 * @param response
	 * @param params AgencyUserEntity
	 * @throws IOException 
	 */
	@RequestMapping(value = "/deletes", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void deletes(HttpServletRequest request, HttpServletResponse response, 
			String ids) throws IOException {
		try {
			boolean flag = false;
			flag = agencyUserService.deletes(getCurrentFactoryUser().getId(),
					getCurrentFactoryUser().getFacId(),
					LongUtils.convert(ids.split("[, ]+")));
			
			doResult(response, flag, flag ? StatusCode.REMOVESUCCESS:StatusCode.REMOVEERROR,
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.SAVEERROR, null, ResultType.SAVE_FAULT);
			e.printStackTrace();
		}
	}
	
	
	/**
	 * Description:经销商用户密码重置
	 * @param response
	 * @param id
	 * @param oldPassword
	 * @param newPassword
	 * @param newPassword2
	 * @author around
	 * @date 2017年8月23日下午5:13:03
	 */
	@RequestMapping(value = "/reset", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void resetPassword(HttpServletResponse response, Long id, String oldPassword, 
			String newPassword, String newPassword2) {
		if (null == id) {
			doResult(response, false, StatusCode.LACKVALUE, null, "缺少用户ID信息");
			return;
		}
		/*if (StringUtils.isEmpty(oldPassword)) {
			doResult(response, false, StatusCode.LACKVALUE, null, "原始密码不能为空");
			return;
		}
		if (StringUtils.isEmpty(newPassword)) {
			doResult(response, false, StatusCode.LACKVALUE, null, "新密码不能为空");
			return;
		}
		if(!newPassword.equals(newPassword2)) {
			doResult(response, false, StatusCode.LACKVALUE, null, "两次新密码输入必须一致");
			return;
		}*/
		try {
			boolean flag = agencyUserService.resetPassword(id, null, 
					DigestUtils.md5Hex("123456"));
			doResult(response, flag, flag ? StatusCode.SAVESUCCESS:StatusCode.SAVEERROR,
					null, flag ? "密码已重置为123456" : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.LACKVALUE, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value = "/exportExcel", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void export(HttpServletRequest request, HttpServletResponse response, 
			String logStatus, String successStatus, ExcelBean bean, 
			Integer page, Integer rows, String sort, String order) {
		
		String serverPath = request.getSession().getServletContext().getRealPath("/");
		
		//列名和字段名
		String[] fields = bean.getColumnStr().split(",");
		String[] titles = bean.getTitleStr().split(",");
		
		
		List<Object> returnList = new ArrayList<Object>();
		
		JSONObject json = new JSONObject();
		ExcelUtils.exportExcel(json, bean.getExcelName(), serverPath, titles, fields, returnList);
		
		doResult(response, true, StatusCode.SAVESUCCESS, json, "导出成功");
	}
	
	
}
